<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑权限' : '新增权限'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入权限名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限代码" prop="code">
            <el-input v-model="form.code" placeholder="请输入权限代码" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权限类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择权限类型" style="width: 100%">
              <el-option 
                v-for="option in PERMISSION_TYPE_OPTIONS" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value" 
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="父级权限" prop="parentId">
            <el-select v-model="form.parentId" placeholder="请选择父级权限" clearable style="width: 100%">
              <el-option 
                v-for="permission in parentPermissionOptions" 
                :key="permission.id" 
                :label="permission.name" 
                :value="permission.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="路径" prop="path">
            <el-input v-model="form.path" placeholder="请输入路径" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="重定向" prop="redirect">
            <el-input v-model="form.redirect" placeholder="请输入重定向路径" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="图标" prop="icon">
            <IconSelector v-model="form.icon" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组件" prop="component">
            <el-input v-model="form.component" placeholder="请输入组件路径" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="布局" prop="layout">
            <el-input v-model="form.layout" placeholder="请输入布局名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="HTTP方法" prop="method">
            <el-select v-model="form.method" placeholder="请选择HTTP方法" clearable style="width: 100%">
              <el-option 
                v-for="option in METHOD_TYPE_OPTIONS" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" prop="order">
            <el-input-number v-model="form.order" :min="0" :max="9999" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="缓存" prop="keepAlive">
            <el-switch v-model="form.keepAlive" active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="显示" prop="show">
            <el-switch v-model="form.show" active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用" prop="enable">
            <el-switch v-model="form.enable" active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入权限描述" 
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { 
  permissionApi, 
  CreatePermissionDto, 
  UpdatePermissionDto, 
  Permission,
  PERMISSION_TYPE_OPTIONS,
  METHOD_TYPE_OPTIONS,
  ICON_OPTIONS
} from '../api/permission'
import IconSelector from './IconSelector.vue'

// Props
interface Props {
  modelValue: boolean
  permission?: Permission | null
  isEdit: boolean
}

const props = withDefaults(defineProps<Props>(), {
  permission: null,
  isEdit: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 表单引用
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

// 提交状态
const submitting = ref(false)

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单数据
const form = reactive<CreatePermissionDto>({
  name: '',
  code: '',
  type: 'MENU',
  parentId: undefined,
  path: '',
  redirect: '',
  icon: '',
  component: '',
  layout: '',
  keepAlive: false,
  method: undefined,
  description: '',
  order: 0,
  show: true,
  enable: true
})

// 父级权限选项
const parentPermissionOptions = ref<Permission[]>([])

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 获取父级权限选项
const fetchParentPermissions = async () => {
  try {
    const res = await permissionApi.getAllPermissions()
    if (res && res.code === 200) {
      parentPermissionOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取父级权限失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    name: '',
    code: '',
    type: 'MENU',
    parentId: undefined,
    path: '',
    redirect: '',
    icon: '',
    component: '',
    layout: '',
    keepAlive: false,
    method: undefined,
    description: '',
    order: 0,
    show: true,
    enable: true
  })
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 填充表单数据
const fillForm = (permission: Permission) => {
  Object.assign(form, {
    name: permission.name,
    code: permission.code,
    type: permission.type,
    parentId: permission.parentId,
    path: permission.path || '',
    redirect: permission.redirect || '',
    icon: permission.icon || '',
    component: permission.component || '',
    layout: permission.layout || '',
    keepAlive: permission.keepAlive || false,
    method: permission.method,
    description: permission.description || '',
    order: permission.order || 0,
    show: permission.show !== false,
    enable: permission.enable !== false
  })
}

// 监听对话框显示状态
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.permission) {
      fillForm(props.permission)
    } else {
      resetForm()
      // 如果是新增模式且有传入的权限信息（添加子权限时），保留父级权限ID
      if (props.permission && props.permission.parentId) {
        form.parentId = props.permission.parentId
      }
    }
    fetchParentPermissions()
  }
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (props.isEdit && props.permission) {
          // 更新权限
          const updateData: UpdatePermissionDto = { ...form }
          const res = await permissionApi.updatePermission(props.permission.id, updateData)
          
          if (res && res.code === 200) {
            ElMessage.success('更新权限成功')
            emit('success')
          } else {
            ElMessage.error('更新权限失败')
          }
        } else {
          // 创建权限
          const createData: CreatePermissionDto = { ...form }
          const res = await permissionApi.createPermission(createData)
          
          if (res && res.code === 200) {
            ElMessage.success('创建权限成功')
            emit('success')
          } else {
            ElMessage.error('创建权限失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
